package com.blockmeta.bbs.businesslibrary.widget.chartview.Layer;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.text.TextUtils;


import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.util.Format2Util;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.Coordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.MoveCoordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CandleData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData;

import java.util.HashMap;
import java.util.List;

class MoveLineLayer extends BasicLayer
{
	protected final double m_dbNone = Double.MIN_VALUE;

	public MoveLineLayer()
	{
		super();
	}

	@Override
	public Coordinate createCoordinate()
	{
		return new MoveCoordinate();
	}

	/**
	 * 获取数据的移动位置
	 * @return
	 */
	protected int getMoveStartIndex()
	{
		Coordinate tCoordinate = m_callback.getCoordinate();
		if(tCoordinate != null)
		{
			return tCoordinate.getStartIndex();
		}
		return 0;
	}

	/**
	 * 获取指标开始绘制的值,因为刚开始指标没有数据
	 * @return
	 */
	protected int getDataStartIndex()
	{
		return getMoveStartIndex();
	}

	@Override
	public Layer.ChartTypeEnum getLayerTypeEnum()
	{
		return Layer.ChartTypeEnum.MoveLine;
	}

	@Override
	public void onDrawLayer(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
		//获取坐标系
		Coordinate tCoordinate = m_callback.getCoordinate();
		//转化处理数据
		List<CandleData> tDataList = convertDate(m_callback.getCandleDataList());

		//定义初始化文本
		String tBeforeCloseText = "";
		String tCloseText = null;
		String tOpenText = null;
		String tHighText = null;
		String tLowText = null;
		String tTimeText = null;
		String tValueText = null;
		float tVolumnText = 0;
		String tAvgText = null;
		int tXPoint = pPoint.x;


		if (tDataList != null && tDataList.size() > 0)
		{
			int tListSize = tDataList.size();
//			int tStartIndex = tCoordinate.getStartIndex();

			float tXFirstPosition = tCoordinate.getXFirstPosition();
			float tXInterval = tCoordinate.getXInterval();
			float tYFirstposition = tCoordinate.getYFirstPosition();  //tCoordinate.getLayerRectF().bottom;
			// float tYFirstposition = tCoordinate.getYFirstPosition();
			float tYMaxValue = tCoordinate.getMaxValue();
			float tYMinValue = tCoordinate.getMinValue();
			float tYValueDist = tYMaxValue - tYMinValue;
			float tYValueLength = tCoordinate.getValueHeight();  //tCoordinate.getLayerRectF().bottom - tCoordinate.getLayerRectF().top;
			// float tYValueLength = tCoordinate.getYInterval() *
			// tCoordinate.getYIntervalCount();

			drawAvgLine(pCanvas, pPaint, tCoordinate, tYFirstposition, tYMinValue,tYMaxValue, tYValueDist, tYValueLength);

			float tCurrentYPosition = 0.f;
			float tTempYPosition = 0.f;
			float tCurrentXPosition = 0.f;
			float tTempXPosition = 0.f;
			
			float tLineWidth = 2.f;
			pPaint.setAntiAlias(true);
			
			boolean tStartDraw = false;

			int tDotColor = BaseApp.getApp().getResources().getColor(R.color.sys_even);
			int tCulOffset = 1;

			boolean isShowShadow = m_callback.isShowShadow();
			Path tAreaPath = new Path();
			RectF tChartRect = tCoordinate.getLayerRectF();
			float tTopPosition = tChartRect.bottom;

			int dataStart = getDataStartIndex(); //tStartIndex + getStartIndex();

			int moveStart = getMoveStartIndex();
			int displayCount = m_callback.getDisplayCount();//获取当前要显示的个数
			int minCount = Math.min(moveStart+displayCount,tListSize);//不能超出数据集宽度

			if(m_callback.isDrawAllData())//如果需要绘制全部数据的
			{
				dataStart = 0;
				moveStart = 0;
				minCount = tListSize;
			}

//			FDTLogUtils.d("tingchart",getLayerTypeEnum()+"layer from draw tStartIndex"+dataStart+" to mincount"+minCount);
			if(dataStart > tListSize)//如果数据量不足以算出一个值
			{
				return;
			}
			for (int i = dataStart; i < minCount; i++)
			{
				//如果收盘价为空就跳过
				if (tDataList.get(i).getDbClose() == m_dbNone)
				{
					continue;
				}

				if(isShowShadow)
				{
					pPaint.setColor(m_callback.getSysBgColor());
				}
				else
				{
					pPaint.setColor(m_callback.getSysBgColor());
				}
				pPaint.setStrokeWidth(tLineWidth);
				
				float tVolumn = (float) tDataList.get(i).getDbClose();

				tTempXPosition = tCurrentXPosition;
				tCurrentXPosition = tXFirstPosition + tXInterval * (i - moveStart);
				tTempYPosition = tCurrentYPosition;
				tCurrentYPosition = tYFirstposition - ((tVolumn - tYMinValue) * tYValueLength / tYValueDist);

				tTopPosition = tTopPosition < tCurrentYPosition ? tTopPosition : tCurrentYPosition;

				//获取涨跌颜色
//				if (tCurrentYPosition > tTempYPosition)
//				{
//					tDotColor = ResourceManager.getColor(FDTApplication.getApp(), "sys_down");
//				}
//				else if (tCurrentYPosition < tTempXPosition)
//				{
//					tDotColor = ResourceManager.getColor(FDTApplication.getApp(), "sys_up");
//				}
//				else
				{
					tDotColor = BaseApp.getApp().getResources().getColor(R.color.sys_even);
				}

				if (((tCurrentXPosition - tXInterval / 2) <= pPoint.x && pPoint.x < (tCurrentXPosition + tXInterval / 2)) || ((i == minCount - 1) && pPoint.x > tCurrentXPosition + tXInterval / 2))
				{
					float tValueaa = (tYFirstposition - pPoint.y) * tYValueDist / tYValueLength + tYMinValue;
					tValueText = FormatUtil.getFormatString(tValueaa, m_callback.getDigit());

					ChartData.ChartPeroid tChartType = m_callback.getChartType();

					tVolumnText = tDataList.get(i).m_lVolume;
					tCloseText = String.valueOf((float) tDataList.get(i).getDbClose());
					tOpenText = String.valueOf((float) tDataList.get(i).getDbOpen());
					tHighText = String.valueOf((float) tDataList.get(i).getDbHigh());
					tLowText = String.valueOf((float) tDataList.get(i).getDbLow());
					tAvgText = String.valueOf((float) tDataList.get(i).m_dbAvgPx);

					tTimeText = getDisplayX(tChartType, tDataList.get(i));

					if(i > 0)
					{
						float tBeforeClose = (float) tDataList.get(i - 1).getDbClose();
						tBeforeCloseText = String.valueOf(tBeforeClose);
					}
					else
					{
						tBeforeCloseText = "0";
					}
					tXPoint = (int) tCurrentXPosition;
				}



				if(isShowShadow)//显示阴影
				{
					if (i == dataStart)
					{
						tAreaPath.moveTo(tXFirstPosition, tChartRect.bottom);
						tAreaPath.lineTo(tXFirstPosition, tCurrentYPosition);
					}
					tAreaPath.lineTo(tCurrentXPosition, tCurrentYPosition);
					if (i == (tListSize - 1))
					{
						tAreaPath.lineTo(tCurrentXPosition, tChartRect.bottom);
						tAreaPath.lineTo(tXFirstPosition, tChartRect.bottom);
					}
				}

//				if (i != tStartIndex/* && tTempXPosition != 0*/)
				if (tStartDraw)
				{
					RectF tRectF = tCoordinate.getLayerRectF();
					
					boolean tTempUpper = (tRectF.top - tCulOffset) <= tTempYPosition ? false : true;
					boolean tTempLowwer = (tRectF.bottom + tCulOffset) >= tTempYPosition ? false : true;
					boolean tCurrentUpper = (tRectF.top - tCulOffset) <= tCurrentYPosition ? false : true;
					boolean tCurrentLowwer = (tRectF.bottom + tCulOffset) >= tCurrentYPosition ? false : true;
					
					if (!tTempUpper && !tTempLowwer && !tCurrentUpper && !tCurrentLowwer)
					{
//						LogUtils.w("DrawLineA", "startX: " + tTempXPosition + " startY: " + tTempYPosition
//							+ " endX: " + tCurrentXPosition + " endY: " + tCurrentYPosition);

						pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);
					}
					else if ((tTempUpper || tTempLowwer) && !tCurrentUpper && !tCurrentLowwer)
					{
						float middle;
						if (tTempUpper)
						{
							middle = tRectF.top;
						}
						else
						{
							middle = tRectF.bottom;
						}
						float tTempX = (tCurrentXPosition - tTempXPosition) * getScale(tTempYPosition, tCurrentYPosition, middle) + tTempXPosition;

						pCanvas.drawLine(tTempX, middle, tCurrentXPosition, tCurrentYPosition, pPaint);
					}
					else if ((tCurrentUpper || tCurrentLowwer) && !tTempUpper && !tTempLowwer)
					{
						float middle;
						if (tCurrentUpper)
						{
							middle = tRectF.top;
						}
						else
						{
							middle = tRectF.bottom;
						}
						float tTempX = (tCurrentXPosition - tTempXPosition) * getScale(tTempYPosition, tCurrentYPosition, middle) + tTempXPosition;

						pCanvas.drawLine(tTempXPosition, tTempYPosition, tTempX, middle, pPaint);
					}
					else
					{
					}
				}
				else
				{
					tStartDraw = true;
				}
				
				if (tDataList.get(i).m_bDrawDot)
				{
					pPaint.setColor(tDotColor);
					pCanvas.drawCircle(tCurrentXPosition, tCurrentYPosition, tLineWidth * 2, pPaint);
				}
			}

			if(isShowShadow)//显示阴影
			{
				Shader mShader = new LinearGradient(0, tTopPosition, 0, tChartRect.bottom,
						Color.argb((Color.alpha(m_callback.getSysBgColor())) / 3, Color.red(m_callback.getSysBgColor()), Color.green(m_callback.getSysBgColor()), Color.blue(m_callback.getSysBgColor())), Color.argb((Color.alpha(m_callback.getSysBgColor())) / 15, Color.red(m_callback.getSysBgColor()), Color.green(m_callback.getSysBgColor()), Color.blue(m_callback.getSysBgColor())), Shader.TileMode.CLAMP);
				pPaint.setShader(mShader);
//			}
//			else
//			{
//				pPaint.setColor(Color.argb((Color.alpha(m_callback.getSysBgColor())) / 5, Color.red(m_callback.getSysBgColor()), Color.green(m_callback.getSysBgColor()), Color.blue(m_callback.getSysBgColor())));
//			}

				pCanvas.drawPath(tAreaPath, pPaint);
				pPaint.reset();
				pPaint.setAntiAlias(true);
			}
		}



		RectF tLayerRect = tCoordinate.getLayerRectF();
		setCrossData(pCanvas, pPaint, tTimeText, tValueText, new Point(tXPoint, pPoint.y));
		if (tLayerRect.contains(tXPoint, pPoint.y))
		{


			if (m_callback != null)
			{
				int tDigit = Math.max(tCoordinate.getDigit(), 1);

				tCloseText = getDigitString(tCloseText, tDigit);
				tOpenText = getDigitString(tOpenText, tDigit);
				tHighText = getDigitString(tHighText, tDigit);
				tLowText = getDigitString(tLowText, tDigit);
				tAvgText = tAvgText == null ? "" : tAvgText;
				HashMap<String, String> tMap = new HashMap<String, String>();
				tMap.put("Close", tCloseText);
				tMap.put("Open", tOpenText);
				tMap.put("High", tHighText);
				tMap.put("Low", tLowText);
				tMap.put("BeforeClose", tBeforeCloseText);
				tMap.put("Volumn", tVolumnText == 0 ? "" : Format2Util.doubleToHumanReadableFormat(tVolumnText, 2));
				tMap.put("Time",tTimeText);
				tMap.put("Avg",tAvgText);
				m_callback.pointFeedback(tMap,pPoint);
			}
		}
	}

	private String getDigitString(String value, int digit)
	{
		if (! TextUtils.isEmpty(value))
		{
			try
			{
				value = FormatUtil.getFormatString(Double.parseDouble(value), digit);
			}
			catch (Exception e)
			{
			}
		}
		else
		{
			value = "";
		}

		return value;
	}
	
	private float getScale(float start, float end, float middle)
	{
		return (start - middle) / (start - end);
	}
	
	public List<CandleData> convertDate(List<CandleData> pList)
	{
		return pList;
	}

	@Override
	public boolean isDrawAvgText() {
		return true;
	}
}
